package com.witframework.web.extremetable;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.core.Messages;
import org.extremecomponents.table.core.TableModelUtils;



/**
 * Load up the resource bundle that will be used by the Model.
 *
 * fix by wuxinyang 增加了对多个用户定义语言文件的支持
 */
public class WsTableResourceBundle implements Messages {
	private static Log logger = LogFactory.getLog(WsTableResourceBundle.class);

	public final static String EXTREMETABLE_RESOURCE_BUNDLE = "org.extremecomponents.table.resource.extremetableResourceBundle";

	private ResourceBundle defaultResourceBundle;
	private Locale locale;

	private String[] basenames = new String[0];

	private final Map cachedResourceBundles = new HashMap();

	public void init(Context context, Locale _locale) {
		this.locale = context.getLocale();
		long startTime=System.currentTimeMillis();
		defaultResourceBundle = findResourceBundle(EXTREMETABLE_RESOURCE_BUNDLE, locale);
		//logger.debug("The resource bundle [ " + EXTREMETABLE_RESOURCE_BUNDLE	+ "] was bundled!");
		String messagesLocation = TableModelUtils.getMessagesLocation(context);
		if (StringUtils.isNotBlank(messagesLocation)) {
			basenames = messagesLocation.split("[\\p{Space}]+");
			for (String basename : basenames) {
				cachedResourceBundles.put(basename, findResourceBundle(
						basename, locale));
				//logger.debug("The resource bundle [ " + basename	+ "] was bundled!");
			}
		}

	}

	private ResourceBundle findResourceBundle(String resourceBundleLocation,
			Locale locale) {
		try {

			return ResourceBundle.getBundle(resourceBundleLocation, locale,Thread.currentThread().getContextClassLoader());
		} catch (MissingResourceException e) {
			if (logger.isErrorEnabled()) {
				logger
						.error(
								"The resource bundle [ "
										+ resourceBundleLocation
										+ "] was not found. Make sure the path and resource name is correct.",
								e);
			}
		}
		return null;
	}

	/**
	 * Get the resource property.
	 */
	public String getMessage(String code) {
		return getMessage(code, null);
	}

	/**
	 * Get the resource property.
	 */
	public String getMessage(String code, Object[] args) {
		String result = findResource(code);
		if (result == null) {
			result = getStringOrNull(defaultResourceBundle, code);
		}

		if (result != null && args != null) {
			MessageFormat formatter = new MessageFormat("");
			formatter.setLocale(locale);
			formatter.applyPattern(result);
			result = formatter.format(args);
		}
		return result;
	}

	private String findResource(String code) {
		String result = null;
		for (int i = 0; result == null && i < this.basenames.length; i++) {
			ResourceBundle bundle = (ResourceBundle) cachedResourceBundles.get(this.basenames[i]);
			if (bundle != null) {
				result = getStringOrNull(bundle, code);
				if(result!=null)
					break;
			}
		}

		return result;

	}

	private String getStringOrNull(ResourceBundle bundle, String key) {
		try {
			return bundle.getString(key);
		} catch (MissingResourceException ex) {
			return null;
		}
	}

}
